<?
/*
 *  GGB - Gelin's Guest Book.
 *  Copyright (C) 2006  Denis Nelubin aka Gelin
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  http://gelin.ru
 *  mailto:den@gelin.ru
 *
 *  Description:    Interface to MySQL database.
 *
 *  History:
 *  2006-06-25  Gelin   Initially created.
 *  2006-01-06  Gelin   query() can accept arrays
 *  2007-01-20  Gelin   insertedID() added
 *  2008-07-31  Gelin   added setting of charset for MySQL 5
 */

require_once('Logger.php');

/**
 *  Inteface to MySQL database.
 */
class MySQL {

    /** Connection to database */
    var $link;

    /** Logger */
    var $log;

    /**
     *  Constructor.
     */
    function MySQL() {
        global $config;
        $this->log = new Logger('MySQL');
        $this->link = @mysql_connect($config['db']['hostname'],
                $config['db']['username'],
                $config['db']['password'])
                or $this->logError();
        @mysql_select_db($config['db']['database'], $this->link)
                or $this->logError();
        if (isset($config['db']['charset'])) {
            $this->query('SET CHARACTER SET ?', $config['db']['charset']);
        }
    }

    /**
     *  Executes SQL query.
     *  @param  $query  SQL query to execute
     *  @param  many query params (this is vararg function), each argument can be array
     *  @return result of executing
     */
    function query($query) {
        global $lang;
        $params = array();
        for ($i = 1; $i < func_num_args(); $i++) {
            $arg = func_get_arg($i);
            if (is_array($arg)) {
                foreach ($arg as $element) {
                    $params[] = $element;
                }
            } else {
                $params[] = $arg;
            }
        }

        $queryParts = explode('?', $query);
        $paramQuery = '';
        $paramIndex = 0;

        foreach ($queryParts as $part) {
            $paramQuery .= $part;
            if ($paramIndex < count($params)) {
                $paramQuery .= $this->quoteSmart($params[$paramIndex]);
                $paramIndex++;
            }
        }

        $result = @mysql_query($paramQuery, $this->link);
        if (!$result) {
            $this->log->fatal($lang['error.database']);
            $this->log->debug('Error in query:<br/>'.$paramQuery.'<br/>'.mysql_error());
            $this->log->debug('Query:<br/>'.$query);
        }
        //echo "Query:<br/>$paramQuery<br/>";
        return $result;
    }

    /**
     *  Retreives row from result returned by query.
     *  @param  $result result from previous call to query
     *  @return one row of result set as associative and numeric array or FALSE if there is no more rows
     */
    function row($result) {
        $result = @mysql_fetch_array($result);
        $this->logError();
        return $result;
    }

    /**
     *  Returns autogenerated ID caused by previous INSERT query.
     *  @return new generated ID
     */
    function insertedID() {
        return mysql_insert_id($this->link);
    }

    /**
     *  Quote SQL request variable to make it safe.
     *  (c) 1997-2005 the PHP Documentation Group
     */
    function quoteSmart($value)
    {
        // NULL value
        if (is_null($value)) {
            $value = 'NULL';
        } else {
            // Stripslashes
            if (get_magic_quotes_gpc()) {
                $value = stripslashes($value);
            }
            // Quote if not integer
            if (!is_numeric($value)) {
                $value = "'" . @mysql_real_escape_string($value, $this->link) . "'";
            }
        }
        return $value;
    }

    /**
     *  Logs latest MySQL error using MySQL logger.
     */
    function logError() {
        global $lang;
        $error = mysql_error();
        if ($error) {
            $this->log->fatal($lang['error.database']);
            $this->log->debug('MySQL error: '.$error);
        }
    }

}

?>